package com.dense.kuiniu.bookborrow.net;

import com.dense.kuiniu.bookborrow.base.Url;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.concurrent.Executors;

/**
 * @author Administrator
 * @date 2021/2/19
 */
public class SocketChecker {
    private boolean isChecking = true;
    private boolean isConnected = false;
    private String hostName;
    private int port;

    private SocketChecker() {
    }

    private static final class Holder {
        private static final SocketChecker INSTANCE = new SocketChecker();
    }

    public static SocketChecker getInstance() {
        return Holder.INSTANCE;
    }

    public void changeAddress() {
        String fullUrl = Url.baseUrl;
        String[] address = fullUrl.split(":");
        if (address.length == 3) {
            hostName = address[1].replace("//", "");
            port = Integer.parseInt(address[2].replace("/", ""));
        }
    }

    public void startCheckServer() {
        changeAddress();
        Executors.newSingleThreadExecutor().submit(mRunnable);
    }

    public boolean isConnected() {
        return isConnected;
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            while (isChecking) {
                Socket socket = null;
                try {
                    Thread.sleep(5000);
                    socket = new Socket();
                    SocketAddress address = new InetSocketAddress(hostName, port);
                    socket.connect(address, 1000);
                    isConnected = true;
                } catch (Exception e) {
                    e.printStackTrace();
                    isConnected = false;
                } finally {
                    try {
                        if (socket != null) {
                            socket.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    };


} 